package backpage.controller;

import backpage.common.Result;
import backpage.entity.Employee;
import backpage.service.EmployeeService;
import backpage.service.DepartmentEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/employee") // 需要拼接到路径中
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentEmployeeService departmentEmployeeService;

    /**
     * 根据id查询员工信息
     * @param  employeeId
     * author 吴文钦
     * @return  员工信息
     */
    @GetMapping("/queryEmpInfoById/{employeeId}")
    public Result<Employee> queryEmpInfoById(@PathVariable("employeeId") Integer employeeId) {
        Employee employee = employeeService.queryEmpInfoById(employeeId);
            return Result.success(employee);
    }

    /**
     * 根据name查询员工信息
     * author 吴文钦
     * @param employeeName
     * @return
     */
    @GetMapping("/queryEmpInfoByEmployeeName/{employeeName}")
    public Result<List<Employee>> queryEmpInfoByEmployeeName(@PathVariable("employeeName") String employeeName) {
        List<Employee> employees = employeeService.queryEmpInfoByEmployeeName(employeeName);
        if (!employees.isEmpty()) {
            return Result.success(employees);
        } else {
            return Result.failure(404, "未找到员工", null);
        }
    }
    /**
     * 查询全部员工信息
     * author 吴文钦
     * @return
     */
    @GetMapping("/queryAllEmpInfo")
    public Result<List<Employee>> queryAllEmpInfo() {
        List<Employee> employees = employeeService.queryAllEmployeeInfo();
        if (!employees.isEmpty()) {
            return Result.success(employees);
        } else {
            return Result.failure(404, "未找到员工", null);
        }
    }
    /**
     * 根据department和role查询员工信息
     * author 吕瑞峰
     * @return
     */
    @GetMapping("/queryEmpByDeptAndRole/{departmentid}/{role}")
    public Result<List<Employee>> queryEmpByDeptAndRole(
            @PathVariable("departmentid") Integer departmentId,
            @PathVariable("role") Integer role) {

        // 参数有效性验证
        if (departmentId == null || role == null) {
            return Result.failure(400, "参数不合法", null);
        }

        List<Employee> employees = employeeService.getoperator(departmentId, role);

        if (!employees.isEmpty()) {
            return Result.success(employees);
        } else {
            return Result.failure(404,
                    String.format("部门[%d]中未找到角色为[%d]的员工", departmentId, role),
                    null);
        }
    }
    /**
     * 根据role查询员工信息
     * author 吴文钦
     * @param role
     * @return
     */
    @GetMapping("/queryEmpInfoByRole/{role}")
    public Result<List<Employee>> queryEmpInfoByRole(@PathVariable("role") Integer role) {
        List<Employee> employees = employeeService.queryEmpInfoByRole(role);
        if (!employees.isEmpty()) {
            return Result.success(employees);
        } else {
            return Result.failure(404, "未找到员工", null);
        }
    }
    /**
     * 根据employeeNo查询员工信息
     * author 吴文钦
     * @param employeeNo
     * @return
     */
    @GetMapping("/queryEmpInfoByEmployeeNo/{employeeNo}")
    public Result<Employee> queryEmpInfoByNo(@PathVariable("employeeNo") String employeeNo) {
        Employee employee = employeeService.queryEmpInfoByEmployeeNo(employeeNo);
        if (employee != null) {
            return Result.success(employee);
        } else {
            return Result.failure(404, "员工不存在", null);
        }
    }

    @GetMapping("/login/{account}/{password}")
    public Result<Employee> login(@PathVariable("account") String account, @PathVariable("password") String password) {
        Employee employee = employeeService.login(account, password);
        if (employee != null) {
            return Result.success(employee);
        } else {
            return Result.failure(401, "账号或密码错误", null);
        }
    }

    @PostMapping("/insertEmpInfo/{employeeName}/{gender}/{employeePhone}/{email}/{departmentId}/{role}/{position}/{hireDate}/{birthDate}/{currentSalaryLevel}/{comments}")
    public Result<?> insertEmpInfo(
            @PathVariable("employeeName") String employeeName,
            @PathVariable("gender") Integer gender,
            @PathVariable("employeePhone") String employeePhone,
            @PathVariable("email") String email,
            @PathVariable("departmentId") Integer departmentId,
            @PathVariable("role") Integer role,
            @PathVariable("position") String position,
            @PathVariable("hireDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date hireDate,
            @PathVariable("birthDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthDate,
            @PathVariable("currentSalaryLevel") Integer currentSalaryLevel,
            @PathVariable("comments") String comments) {

        Employee employee = new Employee();

        String account = employeeService.generateUniqueUsername();
        if(account == null){
            return Result.failure(400, "生成账号失败", null);
        }
        employee.setAccount(account);

        String  userId = departmentEmployeeService.createUserIdByDepartmentId(departmentId);
        employee.setEmployeeNo(userId);

        //员工初始密码
        employee.setPassword("123456789");
        //员工在职状态
        employee.setIsActive(true);

        employee.setEmployeeName(employeeName);
        employee.setGender(gender);
        employee.setEmployeePhone(employeePhone);
        employee.setEmail(email);
        employee.setDepartmentId(departmentId);
        employee.setRole(role);
        employee.setPosition(position);
        employee.setHireDate(hireDate);
        employee.setBirthDate(birthDate);
        employee.setCurrentSalaryLevel(currentSalaryLevel);
        if(comments != null)
            employee.setComments(comments);

        //初始化员工年假时间
        employee.setRemainingAnnualLeave(5);

        boolean result =  departmentEmployeeService.insertEmpInfo(employee);
        if (result) {
            return Result.success(true);
        } else {
            return Result.failure(400, "添加失败", false);
        }
    }

    @PutMapping("/updateEmpInfo")
    public Result<?> updateEmployeeInfo(@RequestBody Employee employee) {
        boolean updateResult = employeeService.updateEmpInfo(employee);
        if (updateResult) {
            return Result.success( true);
        } else {
            return Result.failure(400, "更新失败", false);
        }
    }

    @DeleteMapping("/deleteEmpById/{employeeId}")
    public Result<?> deleteEmployeeById(@PathVariable("employeeId") Integer employeeId) {
        try {
            boolean result = departmentEmployeeService.deleteEmployeeById(employeeId);
            if (result) {
                return Result.success(true);
            } else {
                return Result.failure(400, "删除失败", false);
            }
        } catch (Exception e) {
            return Result.failure(500, "服务器错误", false);
        }
    }
}